package com.xiaozhi.dialogue.service;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
import com.xiaozhi.communication.common.ChatSession;
import com.xiaozhi.communication.common.SessionManager;
import com.xiaozhi.entity.PushMessageRequest;
import com.xiaozhi.service.ITPushSubService;
import jakarta.annotation.Resource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Map;
import java.util.UUID;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ConcurrentHashMap;

@Service
public class PushMessageService {

    @Autowired
    private MessageService messageService;

    @Autowired
    private SessionManager sessionManager;


    @Resource
    private DialogueService dialogueService;
    // 使用ConcurrentHashMap存储正在推送的任务
    private final Map<String, CompletableFuture<Void>> activePushTasks = new ConcurrentHashMap<>();
    @Autowired
    private ObjectMapper objectMapper;

    public void pushMessages(PushMessageRequest request) {
        String pushId = request.getPushId() != null ? request.getPushId() : UUID.randomUUID().toString();
        // 创建推送任务
        CompletableFuture<Void> task = CompletableFuture.runAsync(() -> {
            // 执行推送逻辑
            for (String deviceId : request.getDeviceIds()) {
                ChatSession chatSession = sessionManager.getSessionByDeviceId(deviceId);
                if (chatSession != null && chatSession.isOpen()) {
                    dialogueService.sendFixedTextAndAudio(chatSession, "你好吗");
                }
            }
        });
        // 存储任务到活跃任务列表
        activePushTasks.put(pushId, task);
    }

    public void cancelPush(String pushId) {
        CompletableFuture<Void> task = activePushTasks.remove(pushId);
        if (task != null) {
            task.cancel(true); // 取消任务
        }
    }

    private void sendPushMessage(ChatSession chatSession, PushMessageRequest request) {
        // 发送消息的逻辑
        ObjectNode messageJson = objectMapper.createObjectNode();
        messageJson.put("type", "push");
        messageJson.put("title", request.getTitle());
        messageJson.set("questions", objectMapper.valueToTree(request.getQuestions()));
        messageService.sendTextMessage(chatSession, messageJson.toString());
    }

}
